package com.neusoft.elmboot.service.impl;

import com.neusoft.elmboot.mapper.BusinessMapper;
import com.neusoft.elmboot.mapper.OrdersMapper;
import com.neusoft.elmboot.mapper.UserMapper;
import com.neusoft.elmboot.po.Business;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员服务实现
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public Map<String, Object> getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 获取基本统计数据
            stats.put("totalUsers", userMapper.getUserCount());
            stats.put("totalBusinesses", businessMapper.getBusinessCount());
            stats.put("totalOrders", ordersMapper.getOrderCount());
            stats.put("totalRevenue", ordersMapper.getTotalRevenue());
            
            // 今日数据
            stats.put("todayUsers", userMapper.getTodayUserCount());
            stats.put("todayOrders", ordersMapper.getTodayOrderCount());
            stats.put("todayRevenue", ordersMapper.getTodayRevenue());
            
            // 本月数据
            stats.put("monthlyOrders", ordersMapper.getMonthlyOrderCount());
            stats.put("monthlyRevenue", ordersMapper.getMonthlyRevenue());
            
            // 用户状态统计
            stats.put("activeUsers", userMapper.getActiveUserCount());
            stats.put("inactiveUsers", userMapper.getUserCount() - userMapper.getActiveUserCount());
            
            // 商家状态统计
            stats.put("activeBusinesses", businessMapper.getActiveBusinessCount());
            
            // 计算平均订单金额
            int totalOrders = ordersMapper.getOrderCount();
            java.math.BigDecimal totalRevenue = ordersMapper.getTotalRevenue();
            if (totalOrders > 0 && totalRevenue != null) {
                stats.put("avgOrderAmount", totalRevenue.divide(new java.math.BigDecimal(totalOrders), 2, java.math.RoundingMode.HALF_UP));
            } else {
                stats.put("avgOrderAmount", java.math.BigDecimal.ZERO);
            }
            
        } catch (Exception e) {
            // 如果查询失败，返回默认值
            e.printStackTrace();
            stats.put("totalUsers", 0);
            stats.put("totalBusinesses", 0);
            stats.put("totalOrders", 0);
            stats.put("totalRevenue", java.math.BigDecimal.ZERO);
            stats.put("todayUsers", 0);
            stats.put("todayOrders", 0);
            stats.put("todayRevenue", java.math.BigDecimal.ZERO);
            stats.put("monthlyOrders", 0);
            stats.put("monthlyRevenue", java.math.BigDecimal.ZERO);
            stats.put("activeUsers", 0);
            stats.put("inactiveUsers", 0);
            stats.put("activeBusinesses", 0);
            stats.put("avgOrderAmount", java.math.BigDecimal.ZERO);
        }
        
        return stats;
    }

    // ==================== 用户管理 ====================

    @Override
    public Map<String, Object> getUserList(Integer page, Integer size, String keyword) {
        Map<String, Object> result = new HashMap<>();
        
        int offset = (page - 1) * size;
        List<User> users;
        int total;
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            users = userMapper.searchUsers(keyword.trim(), size, offset);
            total = userMapper.searchUsersCount(keyword.trim());
        } else {
            users = userMapper.getUsersByPage(size, offset);
            total = userMapper.getUserCount();
        }
        
        result.put("users", users);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (int) Math.ceil((double) total / size));
        
        return result;
    }

    @Override
    public void addUser(User user) {
        // 检查用户ID是否已存在
        if (userMapper.checkUserExists(user.getUserId()) > 0) {
            throw new RuntimeException("用户ID已存在");
        }
        
        // 设置默认值
        if (user.getLevel() == null) user.setLevel(1);
        if (user.getPoints() == null) user.setPoints(0);
        if (user.getExperiencePoints() == null) user.setExperiencePoints(0);
        if (user.getDelTag() == null) user.setDelTag(1);
        if (user.getPassword() == null) user.setPassword("123456"); // 默认密码
        
        int result = userMapper.addUser(user);
        if (result <= 0) {
            throw new RuntimeException("添加用户失败");
        }
    }

    @Override
    public void updateUser(User user) {
        if (userMapper.checkUserExists(user.getUserId()) == 0) {
            throw new RuntimeException("用户不存在");
        }
        
        int result = userMapper.updateUser(user);
        if (result <= 0) {
            throw new RuntimeException("更新用户失败");
        }
    }

    @Override
    public void deleteUser(String userId) {
        if (userMapper.checkUserExists(userId) == 0) {
            throw new RuntimeException("用户不存在");
        }
        
        int result = userMapper.deleteUser(userId);
        if (result <= 0) {
            throw new RuntimeException("删除用户失败");
        }
    }

    @Override
    public void updateUserStatus(String userId, Integer status) {
        if (userMapper.checkUserExists(userId) == 0) {
            throw new RuntimeException("用户不存在");
        }
        
        int result = userMapper.updateUserStatus(userId, status);
        if (result <= 0) {
            throw new RuntimeException("更新用户状态失败");
        }
    }

    // ==================== 商家管理 ====================

    @Override
    public Map<String, Object> getBusinessList(Integer page, Integer size, String keyword) {
        Map<String, Object> result = new HashMap<>();
        
        int offset = (page - 1) * size;
        List<Business> businesses;
        int total;
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            businesses = businessMapper.searchBusinesses(keyword.trim(), size, offset);
            total = businessMapper.searchBusinessesCount(keyword.trim());
        } else {
            businesses = businessMapper.getBusinessesByPage(size, offset);
            total = businessMapper.getBusinessCount();
        }
        
        result.put("businesses", businesses);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (int) Math.ceil((double) total / size));
        
        return result;
    }

    @Override
    public void addBusiness(Business business) {
        // 检查商家ID是否已存在
        if (businessMapper.checkBusinessExists(business.getBusinessId()) > 0) {
            throw new RuntimeException("商家ID已存在");
        }
        
        // 设置默认值
        if (business.getOrderTypeId() == null) business.setOrderTypeId(1);
        if (business.getStarPrice() == null) business.setStarPrice(0.0);
        if (business.getDeliveryPrice() == null) business.setDeliveryPrice(0.0);
        // Business实体没有status字段，使用remarks代替
        
        int result = businessMapper.addBusiness(business);
        if (result <= 0) {
            throw new RuntimeException("添加商家失败");
        }
    }

    @Override
    public void updateBusiness(Business business) {
        if (businessMapper.checkBusinessExists(business.getBusinessId()) == 0) {
            throw new RuntimeException("商家不存在");
        }
        
        int result = businessMapper.updateBusiness(business);
        if (result <= 0) {
            throw new RuntimeException("更新商家失败");
        }
    }

    @Override
    public void deleteBusiness(String businessId) {
        if (businessMapper.checkBusinessExists(businessId) == 0) {
            throw new RuntimeException("商家不存在");
        }
        
        int result = businessMapper.deleteBusiness(businessId);
        if (result <= 0) {
            throw new RuntimeException("删除商家失败");
        }
    }

    @Override
    public void updateBusinessStatus(String businessId, Integer status) {
        if (businessMapper.checkBusinessExists(businessId) == 0) {
            throw new RuntimeException("商家不存在");
        }
        
        int result = businessMapper.updateBusinessStatus(businessId, status);
        if (result <= 0) {
            throw new RuntimeException("更新商家状态失败");
        }
    }

    // ==================== 订单管理 ====================

    @Override
    public Map<String, Object> getOrderList(Integer page, Integer size) {
        Map<String, Object> result = new HashMap<>();
        
        int offset = (page - 1) * size;
        List<Map<String, Object>> orders = ordersMapper.getOrdersByPage(size, offset);
        int total = ordersMapper.getOrderCount();
        
        result.put("orders", orders);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (int) Math.ceil((double) total / size));
        
        return result;
    }

    @Override
    public Map<String, Object> getPlatformStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 订单统计
        stats.put("totalOrders", ordersMapper.getOrderCount());
        stats.put("todayOrders", ordersMapper.getTodayOrderCount());
        stats.put("monthlyOrders", ordersMapper.getMonthlyOrderCount());
        
        // 收入统计
        stats.put("totalRevenue", ordersMapper.getTotalRevenue());
        stats.put("todayRevenue", ordersMapper.getTodayRevenue());
        stats.put("monthlyRevenue", ordersMapper.getMonthlyRevenue());
        
        // 用户统计
        stats.put("totalUsers", userMapper.getUserCount());
        stats.put("activeUsers", userMapper.getActiveUserCount());
        
        // 商家统计
        stats.put("totalBusinesses", businessMapper.getBusinessCount());
        stats.put("activeBusinesses", businessMapper.getActiveBusinessCount());
        
        return stats;
    }
}
